<template>
    <div class="account-center">
        <div class="page-center">
            <a-page-header title="账号中心" @back="() => $router.back()"
                style="padding-left: 10px; padding-top: 0"></a-page-header>
            <a-card :bordered="false" style="width: 100%; border-radius: 6px">
                <div class="flex justify-end mb-10">
                    <a-button type="primary" @click="addAccount">
                        <PlusOutlined />添加账号
                    </a-button>
                </div>
                <a-table :dataSource="list" :columns="columns" :pagination="pagination" @change="handleTableChange"
                    rowKey="id" :loading="loading">
                    <template #nickname="{ record }">
                        <div class="source">
                            <img :src="record.avatar" class="source-img">
                            <div>
                                {{ record.nickname }}
                            </div>
                        </div>
                    </template>
                    <template #source="{ record }">
                        {{ record.value }}
                    </template>
                    <template #status_txt="{ record }">
                        <a-tag :color="record.status ? 'green' : 'red'">{{ record.status_txt }}</a-tag>
                    </template>
                    <template #action="{ record }">
                        <a-button type="primary" @click="del(record.id)">删除</a-button>
                    </template>
                </a-table>
            </a-card>
        </div>
        <a-modal :visible="visible" title="选择添加账号的平台" centered :width="700" @cancel="onClose" :footer="null"
            :zIndex="1002">
            <div class="modal-content">
                <div class="app-item" v-for="item in appConfig" :key="item.key" @click="onAddAccount(item.key)">
                    <div class="app-item-img">
                        <img :src="item.image" class="app-img">
                    </div>
                    <div class="app-item-txt">{{ item.value }}</div>
                </div>
            </div>
        </a-modal>
        <account-add-modal v-model:visible="addAccountVisible" :app-key="appKey" :zIndex="1003"
            @logined="onAccountLogined"></account-add-modal>
    </div>
</template>

<script>
import {
    defineComponent,
    reactive,
    toRefs,
    createVNode,
    onMounted,
    watch,
    computed
} from "vue";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
import store from "../../../store/index";
import { Modal, message } from "ant-design-vue";
import { PlusOutlined, ExclamationCircleOutlined } from "@ant-design/icons-vue";
import _ from 'lodash';
import AccountAddModal from "./accountAddModal.vue";

export default defineComponent({
    name: "userSetting",
    components: {
        PlusOutlined,
        ExclamationCircleOutlined,
        AccountAddModal
    },

    setup() {
        const state = reactive({
            total: 0,
            appConfig: [],
            visible: false,
            loading: false,
            list: [],
            columns: [
                {
                    title: "序号",
                    align: "center",
                    dataIndex: "id",
                    key: 'id',
                },
                {
                    title: "账号",
                    align: "center",
                    dataIndex: "nickname",
                    key: 'nickname',
                    slots: {
                        customRender: "nickname",
                    },

                },
                {
                    title: "平台",
                    dataIndex: "source_txt",

                    key: "source_txt",

                    align: "center",
                },
                {
                    title: "登录状态",
                    dataIndex: "status_txt",
                    key: 'status_txt',
                    align: "center",
                    slots: {
                        customRender: "status_txt",
                    },
                },
                {
                    title: "操作",
                    slots: {
                        customRender: "action",
                    },

                    align: "center",
                },
            ],
            pageSize: 10,
            page: 1,

            appKey: "",
            addAccountVisible: false,
        });
        const pagination = computed(() => ({
            total: state.total,
            current: state.page,
            pageSize: state.pageSize,
            showSizeChanger: true,
            showTotal: (total) => `共${total}条`,
        }));
        const handleTableChange = (pager) => {
            state.page = pager.current;
            state.pageSize = pager.pageSize;
            getList()
        }

        const addAccount = () => {
            state.visible = true
        }

        const sendMessage = (type) => {
            window.top.postMessage({ type, })
            state.visible = false
        }

        const onAccountLogined = ({ appKey, headers }) => {
            sendAccountInfo({
                org_id: utils.getOrgId(),
                header: headers,
                source: appKey,
                team_id: store.state.user.teamId,
            })

            state.addAccountVisible = false
            state.visible = false
        }

        const onClose = () => {
            state.visible = false
        }

        const getAppList = () => {
            request.get("/work_ai", "/org/platform/account/list", {}).then((res) => {
                state.loading = false;
                state.appConfig = res.result
            });
        }

        // 发送第三方信息给后台接口
        const sendAccountInfo = (params) => {
            request
                .post("/work_ai", "/org/platform/account/user/sync", params)
                .then((res) => {
                    message.success('授权成功，列表刷新')
                    getList()
                })
                .catch((err) => {
                    console.log(err, 'error');
                    if (err.code == 37100) {
                        return message.error(err.msg)
                    }

                })
        }

        const getList = () => {
            state.loading = true;
            let params = {
                page: state.page,
                pageSize: state.pageSize,
            }

            request.get("/work_ai", "/org/platform/account/user/list", params).then((res) => {
                state.loading = false;
                state.list = res.result.data
                console.log(res, 'resresresresres');

            });

        }

        const initData = () => {
            getList()
            getAppList()
        }

        initData()

        const getTitle = (key) => {
            return _.find(state.appConfig, { key })?.title;
        }

        const del = (id) => {
            Modal.confirm({
                title: () => `确定要删除吗？`,
                icon: () => createVNode(ExclamationCircleOutlined),
                centered: true,
                onOk() {
                    request
                        .del("/work_ai", "/org/platform/account/user/delete", {
                            id,
                        })
                        .then((res) => {
                            message.success("删除成功");
                            getList();
                        });
                },
            });
        }

        const onAddAccount = (key) => {
            state.appKey = key
            state.addAccountVisible = true
        }

        watch(() => state.addAccountVisible, (visible) => {
            if (!visible) {
                state.appKey = ''
            }
        })

        return {
            ...toRefs(state),
            handleTableChange,
            addAccount,
            sendMessage,
            onClose,
            getTitle,
            del,
            onAddAccount,
            onAccountLogined,
            pagination,
        };
    },
});
</script>

<style lang="less" scoped>
.account-center {
    width: 100%;
    height: 100%;
    padding: 20px;
    overflow: hidden auto;

}

.page-center {
    margin: 0 auto;
    max-width: 1200px;
}

.modal-content {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}

.app-item {
    cursor: pointer;
}

.app-item-img {
    display: flex;
    width: 50px;
    height: 50px;
}

.app-img {
    width: 100%;
    height: 100%;
    object-fit: contain;
    border-radius: 5px;
}

.app-item-txt {
    display: flex;
    justify-content: center;
    line-height: 40px;
}

.source {
    display: flex;
    align-items: center;
    justify-content: center;
}

.source-img {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    object-fit: contain;
    margin-right: 5px;
}
</style>